<template>
	<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="新增" width="500px"
		:model-value="visible" @close="onCancel">
		<template #footer>
			<el-button key="back" @click="() => onCancel()">取消</el-button>
			<el-button key="submit" type="primary" :loading="onSubmitLoading" @click="onFinish">提交</el-button>
		</template>

		<el-form :model="modelRef" :rules="rulesRef" ref="formRef" label-width="120px">

			<el-form-item label="角色名称" prop="role_name">
				<el-input v-model="modelRef.role_name" placeholder="请输入角色名称" />
			</el-form-item>
			<el-form-item label="角色说明" prop="description">
				<el-input v-model="modelRef.description" placeholder="请输入角色说明" />
			</el-form-item>
			site:{{site}}
			<el-form-item label="站点" prop="site" v-if="site==0">

				<site-server :siteValue="modelRef.site" :onchange="changeSite"></site-server>
			</el-form-item>
		</el-form>


	</el-dialog>
</template>
<script setup lang="ts">
	import {
		computed,
		defineComponent,
		PropType,
		reactive,
		ref,
		watch
	} from "vue";
	import {
		useI18n
	} from "vue-i18n";
	import {
		TableListItem
	} from "../data.d";
	import { useUserStore } from '@/store/user';
	import {
		ElForm,
		ElMessage
	} from "element-plus";

	interface CreateFormSetupData {
		modelRef : Omit<TableListItem, 'id'>;
		rulesRef : any;
		formRef : typeof ElForm;
		resetFields : () => void;
		onFinish : () => Promise<void>;
	}


	const props = defineProps({

		visible: {
			type: Boolean,
			required: true
		},
		onCancel: {
			type: Function,
			required: true
		},
		onSubmitLoading: {
			type: Boolean,
			required: true
		},
		onSubmit: {
			type: Function as PropType<(values : Omit<TableListItem, 'id'>, resetFields : () => void) =>
				void>,
			required: true
		}
	})

	const user = useUserStore();
	const site = computed(() => user.$state.user.site);


	const {
		t
	} = useI18n();

	// 表单值
	const modelRef = reactive({
		role_name: '',
		description: '',
		site: 0
	});

	// 表单验证
	const rulesRef = reactive({
		role_name: [{
			required: true,
			validator: async (rule : any, value : string) => {
				if (value === '' || !value) {
					throw new Error('请输入名称');
				}
			}
		},],

	});
	// form
	const formRef = ref<typeof ElForm>();
	// 重置
	const resetFields = () => {
		formRef.value && formRef.value.resetFields();
	}
	// 提交
	const onFinish = async () => {
		try {
			const valid : boolean = formRef.value ? await formRef.value.validate() : false;
			if (valid === true) {
				props.onSubmit(modelRef, resetFields);
			}
		} catch (error) {
			// console.log('error', error);
			ElMessage.warning(t('app.global.form.validatefields.catch'));
		}
	};
	watch(() => props.visible, (newValue, oldValue) => {
		if (newValue) {
			modelRef.site = site.value
			console.log('site', site.value)
		}
	})
	const changeSite = (site : number) => {
		modelRef.site = site
	}
</script>